/**
 * Copyright (C), 2015-2021, 开度
 * FileName: MysqlTable
 * Author:   ASUS
 * Date:     2021/5/8 14:31
 * Description: mysql表操作类
 * History:
 * <author>          <time>          <version>          <desc>
 * Hezeyu           2021/5/8           1.0              mysql表操作类
 */
package com.example.spring.security.service;

import com.example.spring.security.config.CreateTableConfig;
import com.example.spring.security.exception.ErrCode;
import com.example.spring.security.utils.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * 〈mysql表操作类〉
 *
 * @author ASUS
 * @create 2021/5/8
 * @since 1.0.0
 */
@Slf4j
@Service
public class MysqlTableService {

    @Autowired
    private CreateTableConfig createTableConfig;

    public BaseResponse createTable(String tableName,String tableSql){
        BaseResponse baseResponse=new BaseResponse();
        try {
            Connection conn = createTableConfig.init();
            //获取数据库表名
            ResultSet rs = conn.getMetaData().getTables(null, null, tableName, null);
            Statement stat = conn.createStatement();
        // 判断表是否存在，如果存在则什么都不做，否则创建表
            if(rs.next() ){
                return baseResponse;
            }
            else{
                // 先判断是否纯在表名，有则先删除表在创建表
//			stat.executeUpdate("DROP TABLE IF EXISTS sys_admin_divisions;CREATE TABLE sys_admin_divisions("
                //创建行政区划表
                stat.executeUpdate(tableSql);
            }
            baseResponse.setSuccess("添加成功",1,"1");
            // 释放资源
            stat.close();
            conn.close();
        } catch (Exception e) {
            baseResponse.setFail("创建失败:"+e.getMessage(),null, ErrCode.paramLackException.getErrCode(),"1");
        }finally {
            return baseResponse;
        }
    }
}
